package com.xzq.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzq.erp.domain.dto.PageDTO;
import com.xzq.erp.domain.dto.SalesOpportunityDTO;
import com.xzq.erp.domain.po.Channel;
import com.xzq.erp.domain.po.Customer;
import com.xzq.erp.domain.po.SalesOpportunity;
import com.xzq.erp.domain.query.SalesOpportunityPageQuery;
import com.xzq.erp.domain.vo.SalesOpportunityVO;
import com.xzq.erp.enums.ResponseCodeEnum;
import com.xzq.erp.exception.BizException;
import com.xzq.erp.mapper.SalesOpportunityMapper;
import com.xzq.erp.service.IChannelService;
import com.xzq.erp.service.ICustomerService;
import com.xzq.erp.service.ISalesOpportunityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzq.erp.utils.PageConvertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售机会表 服务实现类
 * </p>
 *
 * @author xzq
 * @since 2025-05-13
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SalesOpportunityServiceImpl extends ServiceImpl<SalesOpportunityMapper, SalesOpportunity> implements ISalesOpportunityService {

    private final ICustomerService customerService;

    private final IChannelService channelService;

    private final SalesOpportunityMapper salesOpportunityMapper;

    @Override
    public PageDTO<SalesOpportunityVO> getSalesOpportunityList(SalesOpportunityPageQuery query) {
        PageHelper.startPage(query.getCurrent(), query.getSize());
        // 注意Page继承了ArrayList，所以它是个集合对象
        Page<SalesOpportunityVO> page = this.baseMapper.getSalesOpportunityList(query);// 查询分页查询列表
        List<SalesOpportunityVO> result = page.getResult();
        if(CollectionUtils.isEmpty(result)){
            return PageDTO.empty(page.getTotal(), (long)page.getPages());
        }
        log.info("查询结果:{},{}", page.getPages(), page.getTotal());
        return PageDTO.of(page);
    }

    @Override
    public void save(SalesOpportunityDTO salesOpportunityDTO) {
        checkCustomerAndChannel(salesOpportunityDTO);
        SalesOpportunity salesOpportunity = BeanUtil.copyProperties(salesOpportunityDTO, SalesOpportunity.class);
        this.save(salesOpportunity);
    }

    @Override
    public void update(SalesOpportunityDTO salesOpportunityDTO) {
        checkCustomerAndChannel(salesOpportunityDTO);
        SalesOpportunity salesOpportunity = BeanUtil.copyProperties(salesOpportunityDTO, SalesOpportunity.class);
        this.updateById(salesOpportunity);
    }

    /**
     * 校验客户和渠道是否存在
     * @param salesOpportunityDTO
     */
    private void checkCustomerAndChannel(SalesOpportunityDTO salesOpportunityDTO) {
        Long customerId = salesOpportunityDTO.getCustomerId();
        Customer customer = customerService.getById(customerId);
        if(Objects.isNull(customer)){
            throw new BizException(ResponseCodeEnum.CUSTOMER_NOT_EXIST);
        }
        Channel channel = channelService.getById(salesOpportunityDTO.getChannelId());
        if(Objects.isNull(channel)){
            throw new BizException(ResponseCodeEnum.CHANNEL_NOT_EXIST);
        }
    }

    @Override
    public List<SalesOpportunityVO> getAllSalesOpportunities() {
        List<SalesOpportunity> opportunities = this.list();
        List<Long> customerIds = opportunities.stream()
                .map(SalesOpportunity::getCustomerId)
                .collect(Collectors.toList());
        List<Customer> customers = customerService.listByIds(customerIds);
        Map<Long, Customer> customerMap = customers.stream()
                .collect(Collectors.toMap(Customer::getId, customer -> customer));
        List<Long> channelIds = opportunities.stream()
                .map(SalesOpportunity::getChannelId)
                .collect(Collectors.toList());
        List<Channel> channels = channelService.listByIds(channelIds);
        Map<Long, Channel> channelMap = channels.stream()
                .collect(Collectors.toMap(Channel::getId, channel -> channel));
        return opportunities.stream()
                .map(opportunity -> {
                    // 创建VO对象
                    SalesOpportunityVO vo = BeanUtil.toBean(opportunity, SalesOpportunityVO.class);
                    // 获取客户名称
                    if (opportunity.getCustomerId() != null) {
                        Customer customer = customerMap.getOrDefault(opportunity.getCustomerId(),null);
                        if (customer != null) {
                            vo.setCustomerName(customer.getCustomerName());
                        }
                    }
                    // 获取渠道名称
                    if (opportunity.getChannelId() != null) {
                        Channel channel = channelMap.getOrDefault(opportunity.getChannelId(),null);
                        if (channel != null) {
                            vo.setChannelName(channel.getChannelName());
                            vo.setChannelType(channel.getChannelType());
                        }
                    }
                    return vo;
                })
                .collect(Collectors.toList());
    }
}
